package com.oig.sys.msg.app.impl;

import com.oig.common.exception.ServiceException;
import com.oig.sys.msg.app.IAppExportTaskService;
import com.oig.sys.msg.file.IDepFileDownloadService;
import com.oig.sys.msg.service.ITbExportTaskService;
import com.oig.sys.msg.vo.ExportTaskVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;

@Component
@Slf4j
@RequiredArgsConstructor
public class AppExportTaskServiceImpl implements IAppExportTaskService {

    private final ITbExportTaskService exportTaskService;

    private final IDepFileDownloadService depFileDownloadService;


    @Override
    public ResponseEntity<byte[]> download(Integer exportTaskId) {
        ExportTaskVo exportTaskVo = this.exportTaskService.updateDown(exportTaskId);
        try{
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/octet-stream");
            headers.add("Connection", "close");
            headers.add("Accept-Ranges", "bytes");
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportTaskVo.getFileName(), "UTF-8"));
            ResponseEntity<byte[]> erpRes = depFileDownloadService.download(exportTaskVo.getFileId());
            return new ResponseEntity<>(erpRes.getBody(), headers, HttpStatus.OK);
        } catch (Exception e){
            log.error("download file error ", e);
            throw new ServiceException("下载文件失败");
        }
    }


}
